package com.itzdm.reggie.controller;

import com.itzdm.reggie.common.Result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
@Api("通用接口")
public class CommonController {

    @Value("${reggie.path}")
    private String pathBase;

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("上传文件接口")
    public Result<String> upload(MultipartFile file) {
        log.info("文件上传：{}", file.toString());


        String originalFilename = file.getOriginalFilename();
        String filename = UUID.randomUUID().toString();
        originalFilename = filename + originalFilename.substring(originalFilename.lastIndexOf("."));
        try {
            file.transferTo(new File(pathBase + originalFilename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success(originalFilename);
    }


    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    @ApiOperation("文件下载接口")
    private void download(String name, HttpServletResponse response) throws IOException {
        //通过输入流读取文件
        FileInputStream fis = new FileInputStream(new File(pathBase + name));
        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType("image/jpeg");
        int length = 0;
        byte[] bytes = new byte[1024];
        while ((length = fis.read(bytes)) != -1) {
            outputStream.write(bytes, 0, length);
            outputStream.flush();
        }
        outputStream.close();
        fis.close();

    }
}
